/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package facade;

import java.text.SimpleDateFormat;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import remoteEntity.Comment;

/**
 * Stores and retieves data from the comment table.
 * This version uses native mysql-queries.
 * @author vho@kth.se
 */
@Stateless
public class CommentFacade extends AbstractFacade<Comment> {

    @PersistenceContext(unitName = "filecityeePU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CommentFacade() {
        super(Comment.class);
    }

    public int countFileId(Integer fileId) {
        try {
            int count =  ((Long) em.createNativeQuery("select COUNT(*) from comment where filedescription_id="+fileId+";").getSingleResult()).intValue();
            return count;
        } catch (NoResultException e) {
            return 0;
        }
    }

    public void addComment(Comment c) {
        System.out.println("Will add message " + c.getMessage() + " to id " + c.getId());
        //approach 2
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//("dd-MMM-yyyy HH:mm:ss");
        String formattedDate = formatter.format(c.getTimestamp());
        String query = "insert into comment values(null,'" + c.getMessage() + "','" + formattedDate + "'," + c.getFiledescriptionId() + "," + c.getUserId() + ");";
        //System.out.println(query);
        em.createNativeQuery(query).executeUpdate();

    }

    public List findByFileId(Integer fileId, int[] range) {
        try {
            List<Comment> list2 = em.createNativeQuery("Select * from comment where filedescription_id = " + fileId, Comment.class).getResultList();
            //System.out.println("findByFileId result :"+list2+" length: "+list2.size());
            return list2;
        } catch (NoResultException e) {
            return null;
        }
    }
}
